<?php

if (!(isset($debug))) {
   $debug = 0;
}
# expects glibdir to be set in the calling function
if (!isset($glibdir)) {
   $glibdir = "/var/www/html/lib/jpgraph/";
   #$glibdir = "./jpgraph/";
}
include "$glibdir/jpgraph.php";
include "$glibdir/jpgraph_line.php";
include "$glibdir/jpgraph_log.php";
include "$glibdir/jpgraph_bar.php";
include "$glibdir/jpgraph_scatter.php";
include "$glibdir/jpgraph_regstat.php";
include ("$glibdir/jpgraph_error.php");
include ("$glibdir/jpgraph_pie.php");
include ("$glibdir/jpgraph_pie3d.php");


/* *************************************************** */
/* ***********     Plotting Functions    ************ */
/* *************************************************** */


function showGenericPie($listobject, $goutdir, $gouturl, $graphrecs, $xcol, $ycol, $title, $width, $height, $debug) {

   if (count($graphrecs) > 0) {
      $xdata = array();
      $ydata = array();
   } else {
      $xdata = array(0);
      $ydata = array(0);
   }

   $scalemax = 0;
   foreach ($graphrecs as $thisrec) {
      $xval = $thisrec[$xcol];
      $yval = $thisrec[$ycol];
      array_push($xdata, $xval);
      array_push($ydata, $yval);

      if ($yval > $scalemax) {
         $scalemax = $mm;
      }

   }


   $graph = new PieGraph($width, $height,"auto");
   $graph->SetShadow();

   $graph->title->Set("$title");
   $graph->title->SetFont(FF_FONT1,FS_BOLD);

   $p1 = new PiePlot3D($ydata);
   $p1->SetCenter(0.35);
   $p1->SetLegends($xdata);
#   if ($exsl > 0) {
#      $p1->ExplodeSlice($exsl);
#   }

   $graph->Add($p1);
   $gfname = "lupie" . ".$luname." . $thisyear . md5(uniqid(time()));
   $graph->Stroke("$goutdir/$gfname.gif");
   $outinfo = "$gouturl/$gfname.gif";
   if ($debug) { print_r("$outinfo"); }

   return $outinfo;

}


function showGenericNamedPie($listobject, $goutdir, $gouturl, $graphrecs, $xcol, $ycol, $title, $width, $height, $gfname, $prefs, $debug) {

   if (count($graphrecs) > 0) {
      $xdata = array();
      $ydata = array();
   } else {
      $xdata = array(0);
      $ydata = array(0);
   }

   $scalemax = 0;
   foreach ($graphrecs as $thisrec) {
      $xval = $thisrec[$xcol];
      $yval = $thisrec[$ycol];
      array_push($xdata, $xval);
      array_push($ydata, $yval);

      if ($yval > $scalemax) {
         $scalemax = $mm;
      }

   }


   $graph = new PieGraph($width, $height,"auto");
   $graph->SetShadow();
   $graph->SetFrame( 0, array(0,0,0), 0);
   if (isset($prefs['transparent'])) {
      $graph->img->SetTransparent($prefs['transparent']);
   }
   if (isset($prefs['margincolor'])) {
      $graph->SetMarginColor($prefs['margincolor']);
   }


   $graph->title->Set("$title");
   $graph->title->SetFont(FF_FONT1,FS_BOLD);

   if (isset($prefs['3d'])) {
      $p1 = new PiePlot3D($ydata);
   } else {
      $p1 = new PiePlot($ydata);
   }

   if (isset($prefs['showvalues'])) {
      $p1->value->Show($prefs['showvalues']);
   }
   if (isset($prefs['piescale'])) {
      $p1->setSize($prefs['piescale']);
   }

   $p1->setTheme("water");
   #$p1 = new PiePlot($ydata);
   if ($prefs['piecenter']) {
      $piecenter = $prefs['piecenter'];
   }

   if ($prefs['uselegend']) {
      $piecenter = 0.35;
      if ($prefs['piecenter']) {
         $piecenter = $prefs['piecenter'];
      }
      $p1->SetCenter($piecenter);
      $p1->SetLegends($xdata);
   } else {
      $piecenter = 0.5;
      if ($prefs['piecenter']) {
         $piecenter = $prefs['piecenter'];
      }
      $p1->SetCenter($piecenter);
   }
#   if ($exsl > 0) {
#      $p1->ExplodeSlice($exsl);
#   }


   $graph->Add($p1);
   $graph->Stroke("$goutdir/$gfname.gif");
   $outinfo = "$gouturl/$gfname.gif";
   if ($debug) { print_r("$outinfo"); }

   return $outinfo;

}

function showGenericBar($listobject, $goutdir, $gouturl, $graphrecs, $xcol, $ycol, $color, $title, $xlabel, $ylabel, $debug) {

   if (count($graphrecs) > 0) {
      $xdata = array();
      $ydata = array();
   } else {
      $xdata = array(0);
      $ydata = array(0);
   }

   $scalemax = 0;
   foreach ($graphrecs as $thisrec) {
      $xval = $thisrec[$xcol];
      $yval = $thisrec[$ycol];
      array_push($xdata, $xval);
      array_push($ydata, $yval);

      if ($yval > $scalemax) {
         $scalemax = $mm;
      }

   }

#   print ("step 2<br>");
   // Create the graph.
   $graph = new Graph(400,200,"auto");
   $graph->SetScale("intlin");
   $graph->img->SetMargin(60,100,20,40);
   $graph->SetShadow();

   // Create the bar plot
   $eplot = new BarPlot($ydata);
   $eplot->SetFillColor($color);
   $eplot->SetLegend($ylabel);

   // Add the plots to the graph
   $graph->Add($eplot);

   $graph->title->Set("$title");
   $graph->xaxis->title->Set("$xlabel");
   $graph->yaxis->title->Set("$ylabel");
   $graph->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->SetTickLabels($xdata);

   // Display the graph
   $gfname = "$ycol." . md5(uniqid(time())) . "." . DEFAULT_GFORMAT;
   $gpath = "$goutdir/$gfname";
   $gurl = "$gouturl/$gfname";
   $graph->Stroke($gpath);
   return $gurl;
}

function showGenericMultiPlot($goutdir, $gouturl, $inrecs, $debug) {

   # allows mergin of all kinds of plots in a single graph
   # $indata  - array containing multiple data sets and info describing these data sets
   # 'title' -0 title of the graph
   # 'xlabel' - label for X-axis
   # 'bargraphs' - a collection for each bar graph to create, containing the following:
   #    'graphrecs' - the records to graph
   #    'xcol' -
   #    'ycol' -
   #    'color' -
   #    'ylegend' - legend entry for this dataset
//$debug = 1;
   if ($debug) {
      error_log("showGenericMultiPlot() called" . print_r(array_keys($inrecs),1) . "<br>");
   }
   # load data
   // if no data is defined, we simply return
   if (!isset($inrecs['bargraphs'])) {
      return '';
   }
   $bargraphs = $inrecs['bargraphs'];
   $title = $inrecs['title'];
   $xlabel = $inrecs['xlabel'];
   if(isset($inrecs['ylabel'])) {
      $ylabel = $inrecs['ylabel'];
   } else {
      $ylabel = "";
   }
   if(isset($inrecs['x_interval'])) {
      $x_interval = $inrecs['x_interval'];
   } else {
      $x_interval = -1;
   }

   if ($x_interval == '') { $x_interval = -1; }
   if (isset($inrecs['labelangle'])) {
      $labelangle = $inrecs['labelangle'];
   } else {
      $labelangle = 0.0;
   }
   # if there are multiple Y-axis, which set of plots goes in front? 1 ot 2
   if (isset($inrecs['frontaxis'])) {
      $frontaxis = $inrecs['frontaxis'];
   } else {
      $frontaxis = 1;
   }

   if (isset($inrecs['xpos'])) {
      $xpos = $inrecs['xpos'];
   } else {
      $xpos = "min";
   }

   if(isset($inrecs['y2label'])) {
      $y2label = $inrecs['y2label'];
   } else {
      $y2label = "";
   }
   if (isset($inrecs['num_xlabels'])) {
      $numxlabels = $inrecs['num_xlabels'];
   } else {
      $numxlabels = 5;
   }
   if (isset($inrecs['gheight'])) {
      $gheight = $inrecs['gheight'];
   } else {
      $gheight = 300;
   }
   if (!is_numeric($gheight)) {
      $gheight = 300;
   }
   if (isset($inrecs['gwidth'])) {
      $gwidth = $inrecs['gwidth'];
   } else {
      $gwidth = 400;
   }
   if (!is_numeric($gwidth)) {
      $gwidth = 400;
   }
   if ($debug) {
      error_log("Setting graph height = $gheight and width = $gwidth");
   }
   if (isset($inrecs['basename'])) {
      $basename = $inrecs['basename'];
   } else {
      $basename = '';
   }
   if (isset($inrecs['randomname'])) {
      $randomname = $inrecs['randomname'];
   } else {
      $randomname = 1;
   }
   if(isset($inrecs['scale'])) {
      $scale = $inrecs['scale'];
   } else {
      $scale = "intlin";
   }
   if(isset($inrecs['y2scale'])) {
      $y2scale = $inrecs['y2scale'];
   } else {
      $y2scale = "lin";
   }
   if ($debug) {
      $copy = $bargraphs;
      foreach ($copy as $key => $value) {
         $copy[$key]['graphrecs'] = array_slice($value['graphrecs'],0,2);
      }
      //error_log("Input array" . print_r($copy,1) . "<br>");
   }

   # set up the initial graph container
   // Create the graph.
   $graph = new Graph($gwidth,$gheight,"auto");
   if (isset($inrecs['ymax']) and isset($inrecs['ymin']) ) {
      if (isset($inrecs['xmax']) and isset($inrecs['xmin']) ) {
         $graph->SetScale("$scale", $inrecs['ymin'], $inrecs['ymax'], $inrecs['xmin'], $inrecs['xmax']);
      } else {
         $graph->SetScale("$scale", $inrecs['ymin'], $inrecs['ymax']);
      }
   } else {
      $graph->SetScale("$scale");
   }

   if (isset($inrecs['legendlayout'])) {
      $legendlayout = $inrecs['legendlayout'];
   } else {
      $legendlayout = LEGEND_VERT;
   }

   if (isset($inrecs['legendpos'])) {
      $legendpos = $inrecs['legendpos'];
   } else {
      $legendpos = '';
   }

   $graph->legend->SetLayout("$legendlayout");
   if ($debug) {
      error_log("Setting legend position [ " . join(" ",$legendpos) . " ] ");
   }
   if ($legendpos <> '') {
      $graph->legend->Pos($legendpos[0],$legendpos[1],$legendpos[2],$legendpos[3]);
   }

   # automatically calculate margins
      
   $xlabelmargin = $gheight * 0.15;
   $ylabelmargin = $gwidth * 0.1;
   if ($legendlayout == LEGEND_VERT) {
      # calculate legen margin from max legend text width
      $maxleg = 0;
      foreach ($bargraphs as $thisgraph) {
         $ylegend = $thisgraph['ylegend'];
         if (strlen($ylegend) > $maxleg) {
            $maxleg = strlen($ylegend);
         }
      }
      $legendmargin = $maxleg * 9 + 12;
   } else {
      $legendmargin = $gwidth * 0.1;
   }
   $xlabelmargin = $xlabelmargin + abs($xlabelmargin * sin(2.0*3.14159*$labelangle/360.0));
   if ($debug) {
      error_log("Setting margins [ SetMargin($ylabelmargin,$legendmargin,20,$xlabelmargin) ] ");
   }
   if (!($legendmargin > (0.5 * $gwidth)) ) {
      $graph->img->SetMargin($ylabelmargin,$legendmargin,20,$xlabelmargin);
   }
   if ($debug) {
      error_log("Setting shadow");
   }
   $graph->SetShadow();


   $x = 0;
   $x2 = 0;
   $maxrecs = 0;
   $eplot = array();
   $axissss = array();
   $eplot2 = array(); # y-axis 2 if any occur
   $solo_plot1 = array();
   $group_plot1 = array();
   $solo_plot2 = array();
   $group_plot2 = array();
   $allplots = array();
   $error_code = 0; // defaults to ok
   $gerror = '';
   if ($debug) {
      error_log("Iterating through bar graphs: " . count($bargraphs) . " total graphs to add.");
   }
   foreach ($bargraphs as $thisgraph) {
      $graphrecs = $thisgraph['graphrecs'];
      $xcol = $thisgraph['xcol'];
      $ycol = $thisgraph['ycol'];
      $color = $thisgraph['color'];
      $ylegend = $thisgraph['ylegend'];
      if(isset($thisgraph['alpha'])) {
         $alpha = $thisgraph['alpha'];
         $color .= '@' . $alpha;
      }
      $fillcolor = $color;
      if(isset($thisgraph['fillcolor'])) {
         $fillcolor = $thisgraph['fillcolor'];
         if(isset($thisgraph['alpha'])) {
            $alpha = $thisgraph['alpha'];
            $fillcolor .= '@' . $alpha;
         }
      }
      if(isset($thisgraph['overlaptype'])) {
         $overlaptype = $thisgraph['overlaptype'];
      } else {
         $overlaptype = 'sidebyside'; # defaults to no overlap
      }
      if(isset($thisgraph['plottype'])) {
         $plottype = $thisgraph['plottype'];
      } else {
         $plottype = 'bar';
      }
      if (count($graphrecs) > 0) {
         $xdata = array();
         $ydata = array();
      } else {
         $xdata = array(0);
         $ydata = array(0);
      }

      $scalemax = 0;
      foreach ($graphrecs as $thisrec) {
         if (!in_array($xcol, array_keys($thisrec)) and ($error_code <> 1) ) {
            $gerror .= "Error: '$xcol' does not exist in " . print_r($thisrec,1) . " <br>\n";
            $error_code = 1;
            //break;
         }
         if (!in_array($ycol, array_keys($thisrec)) and ($error_code <> 1) ) {
            $gerror .= "Error: '$ycol' does not exist in" . print_r($thisrec,1) . "<br>\n";
            $error_code = 1;
            //break;
         }
         $xval = $thisrec[$xcol];
         $yval = $thisrec[$ycol];
         // this does not yet work, we should eventually have some validation, but this code is not it!
         /*
         if (!is_numeric($xval)) {
            $gerror .= "Error: x-value ( $xval ) is not numeric <br>\n";
            $error_code = 1;
         }
         if (!is_numeric($yval)) {
            $gerror .= "Error: y-value ( $yval ) is not numeric <br>\n";
            $error_code = 1;
         }
         if ( is_numeric($xval) and is_numeric($yval) ) {
            array_push($xdata, $xval);
            array_push($ydata, $yval);

            if ($yval > $scalemax) {
               $scalemax = $yval;
            }
         }
         */
         array_push($xdata, $xval);
         array_push($ydata, $yval);

         if ($yval > $scalemax) {
            $scalemax = $yval;
         }

      }
      $numx = count($xdata);
      if ($numx == 0) {
         $gerror .= "Error: No valid x-values were found <br>\n";
         $error_code = 1;
      }
      $numy = count($ydata);
      if ($numy == 0) {
         $gerror .= "Error: No valid y-values were found <br>\n";
         $error_code = 1;
      }
      if ($x_interval <= 0) {
         $x_interval = intval($numx / $numxlabels);
         if (!($x_interval > 0)) {
            $x_interval = 1;
         }
         if ($debug) {
            error_log("X print interval = $x_interval <br>");
         }
         $graph->xaxis->SetTextLabelInterval($x_interval);
         if ($debug) {
            error_log("Finished Setting X print interval <br>");
         }
      }

      # allows user to specify a second axis
      if(isset($thisgraph['yaxis'])) {
         $yaxis = $thisgraph['yaxis'];
      } else {
         $yaxis = 1;
      }
      if ($debug) {
         error_log("Selecting Plot Type<br>");
      }
      if ( ($numx == 0) or ($numy == 0) ) {
         if ($debug) {
            error_log("Empty Values Entered (numx = $numx / numy = $numy )<br>");
            error_log("Error Message: $gerror<br>");
         }
         return '';
      }
      
      switch ($plottype) {
         case 'bar':
            // Create the bar plot
            if ($debug) {
               error_log("Plot Type 'bar' selected<br>");
               error_log("Adding $numy records <br>");
            }
            $eplot[$x] = new BarPlot($ydata);
            if ($debug) {
               error_log("Plot addeded<br>");
               error_log("Setting Fill Color <br>");
            }
            $eplot[$x]->SetFillColor($color);
            if ($debug) {
               error_log("Fill color set = $color<br>");
            }
         break;

         case 'line':
            # lines are always overlap type 'overlay'
            $overlaptype = 'overlay';
            if ($debug) {
               error_log("Plot Type 'line' selected<br>");
               error_log("Adding $numy records <br>");
            }
            $eplot[$x] = new LinePlot($ydata);
            if(isset($thisgraph['mark'])) {
               $mark = $thisgraph['mark'];
               if ($debug) {
                  error_log("Setting Mark Type<br>");
               }
               $eplot[$x]->mark->SetType($mark);
               if ($debug) {
                  error_log("Mark Type set to = $mark<br>");
               }
            }
            if(isset($thisgraph['weight'])) {
               $weight = $thisgraph['weight'];
               if ($debug) {
                  error_log("Setting Weight<br>");
               }
               $eplot[$x]->SetWeight($weight);
               if ($debug) {
                  error_log("Weight set to = $weight<br>");
               }
            }

            $eplot[$x]->SetColor($color);
            if (isset($thisgraph['filled'])) {
               if ($thisgraph['filled']) {
                  if ($debug) {
                     error_log("Setting Fill Color<br>");
                  }
                  $eplot[$x]->SetFillColor($color);
                  if ($debug) {
                     error_log("Fill Color set = $color<br>");
                  }
               }
            }
         break;

         default:
            // Create the bar plot
            if ($debug) {
               error_log("Unrecognized type $plottype - defaulting to 'bar' <br>");
               error_log("Adding $numy records <br>");
            }
            $eplot[$x] = new BarPlot($ydata);
            if ($debug) {
               error_log("Plot addeded<br>");
               error_log("Setting Fill Color <br>");
            }
            $eplot[$x]->SetFillColor($color);
            if ($debug) {
               error_log("Fill color set = $color<br>");
            }
         break;

      }
      if ($debug) {
         error_log("Plot Type Set to - $plottype <br>");
      }

      # set the legend entry for this plot
      $eplot[$x]->SetLegend($ylegend);

      if (!isset($allplots[$yaxis][$overlaptype])) {
         $allplots[$yaxis][$overlaptype] = array();
      }
      array_push($allplots[$yaxis][$overlaptype], $eplot[$x]);
      $x++;

      array_push($axissss, $yaxis);
      if (count($xdata) > $maxrecs) {
         $graph->xaxis->SetTickLabels($xdata);
         $maxrecs = count($xdata);
      }
   }

   # now render the different graphs by axis, and overlaptype
   $axisgroups = array();
   if ($debug) {
      error_log("Allplots variable = " . print_r(array_keys($allplots),1) );
   }

   foreach (array_keys($allplots) as $thisaxis) {
      $axisplots = $allplots[$thisaxis];

      foreach (array_keys($axisplots) as $thisovertype) {

         switch ($thisovertype) {

            case 'accum':
               # stash in the axis group, if there is only one, it is OK
               $gbarplot = new AccBarPlot($allplots[$thisaxis][$thisovertype]);
               if (!isset($axisgroups[$thisaxis])) {
                  $axisgroups[$thisaxis] = array();
               }
               array_push($axisgroups[$thisaxis], $gbarplot);
            break;

            case 'sidebyside':
               # stash in the axis group, if there is only one, it is OK
               $gbarplot = new GroupBarPlot($allplots[$thisaxis][$thisovertype]);
               if (!isset($axisgroups[$thisaxis])) {
                  $axisgroups[$thisaxis] = array();
               }
               array_push($axisgroups[$thisaxis], $gbarplot);
            break;

            case 'overlay':
               foreach ($allplots[$thisaxis][$thisovertype] as $thisplot) {
                  switch ($thisaxis) {
                     case 1:
                        $graph->Add($thisplot);
                     break;

                     case 2:
                        $graph->AddY2($thisplot);
                     break;

                  }
               }
            break;
         }
      }
   }

   # now, if we have stashed any plots that need to be side by side on the same axis, we display them now
   foreach (array_keys($axisgroups) as $thisaxis) {
      $group_plots = new GroupBarPlot($axisgroups[$thisaxis]);
      #print("Grouping " . count($group_plots) . " on axis $yaxis<br>");
      switch ($thisaxis) {
         case 1:
            $graph->Add($group_plots);
         break;

         case 2:
            $graph->AddY2($group_plots);
         break;

      }
   }

   if (isset($allplots[2])) {
      if (isset($inrecs['y2max']) and isset($inrecs['y2min']) ) {
         $graph->SetY2Scale("$y2scale", $inrecs['y2min'], $inrecs['y2max']);
      } else {
         $graph->SetY2Scale("$y2scale");
      }
      $graph->y2axis->SetTitle("$y2label", "middle");
   }
   $graph->title->Set("$title");
   $graph->xaxis->SetTitle("$xlabel", "middle");
   $graph->yaxis->SetTitle("$ylabel", "middle");
   $graph->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
   if (isset($allplots[2])) {
      $graph->y2axis->title->SetFont(FF_FONT1,FS_BOLD);
   }
   $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->SetPos($xpos);
   #$graph->SetAxisStyle(AXSTYLE_BOXOUT);
   # if the 2nd axis should be in front, tell jpgraph
   if ($frontaxis == 2) {
      $graph->SetY2OrderBack(FALSE);
   }
   $graph->xaxis->setLabelAngle($labelangle);

   // Display the graph
   if ( ($randomname) or (strlen($basename) == 0) ) {
      $gfname = $ycol . "." . md5(uniqid(time())) . "." . DEFAULT_GFORMAT;
   } else {
      $gfname = $basename . "." . DEFAULT_GFORMAT;
   }
   error_log ("Multiplot Graphic format set to " . DEFAULT_GFORMAT);
   error_log ("Error Code: $error_code ");
   $gpath = "$goutdir/$gfname";
   $gurl = "$gouturl/$gfname";
   if ((!$error_code)) {
      try {
         @$graph->Stroke($gpath);
      } catch (Exception $e) {
         error_log( 'Caught exception: ',  $e->getMessage(), "\n");
      }
   } else {
      error_log("Graphing error in lib_plot.pgp - $gerror");
   }
   return $gurl;
}

function showGenericMultiBar($goutdir, $gouturl, $inrecs, $debug) {

   # $indata  - array containing multiple data sets and info describing these data sets
   # 'title' -0 title of the graph
   # 'xlabel' - label for X-axis
   # 'bargraphs' - a collection for each bar graph to create, containing the following:
   #    'graphrecs' - the records to graph
   #    'xcol' -
   #    'ycol' -
   #    'color' -
   #    'ylegend' - legend entry for this dataset

   # load data
   $bargraphs = $inrecs['bargraphs'];
   $title = $inrecs['title'];
   $xlabel = $inrecs['xlabel'];
   if(isset($inrecs['ylabel'])) {
      $ylabel = $inrecs['ylabel'];
   } else {
      $ylabel = "";
   }
   if (isset($inrecs['labelangle'])) {
      $labelangle = $inrecs['labelangle'];
   } else {
      $labelangle = 0.0;
   }

   if(isset($inrecs['y2label'])) {
      $y2label = $inrecs['y2label'];
   } else {
      $y2label = "";
   }
   if (isset($inrecs['overlapping'])) {
      $overlapping = $inrecs['overlapping'];
   } else {
      $overlapping = 1;
   }
   if (isset($inrecs['overlaptype'])) {
      $overlaptype = $inrecs['overlaptype'];
   } else {
      $overlaptype = ''; # setting to type 'accum' will accumulate the bars
   }
   if (isset($inrecs['num_xlabels'])) {
      $numxlabels = $inrecs['num_xlabels'];
   } else {
      $numxlabels = 5;
   }
   if (isset($inrecs['gheight'])) {
      $gheight = $inrecs['gheight'];
   } else {
      $gheight = 200;
   }
   if (isset($inrecs['gwidth'])) {
      $gwidth = $inrecs['gwidth'];
   } else {
      $gwidth = 400;
   }
   if (isset($inrecs['basename'])) {
      $basename = $inrecs['basename'];
   } else {
      $basename = '';
   }
   if (isset($inrecs['randomname'])) {
      $randomname = $inrecs['randomname'];
   } else {
      $randomname = 1;
   }
   if(isset($inrecs['scale'])) {
      $scale = $inrecs['scale'];
   } else {
      $scale = "intlin";
   }
   if(isset($inrecs['y2scale'])) {
      $y2scale = $inrecs['y2scale'];
   } else {
      $y2scale = "lin";
   }
   if ($debug) {
      print_r($bargraphs);
   }

   # set up the initial graph container
   // Create the graph.
   $graph = new Graph($gwidth,$gheight,"auto");
   $graph->SetScale("$scale");
   $graph->img->SetMargin(60,100,20,40);
   $graph->SetShadow();

   $x = 0;
   $x2 = 0;
   $maxrecs = 0;
   $eplot = array();
   $axissss = array();
   $eplot2 = array(); # y-axis 2 if any occur
   $solo_plot1 = array();
   $group_plot1 = array();
   $solo_plot2 = array();
   $group_plot2 = array();
   foreach ($bargraphs as $thisgraph) {
      $graphrecs = $thisgraph['graphrecs'];
      $xcol = $thisgraph['xcol'];
      $ycol = $thisgraph['ycol'];
      $color = $thisgraph['color'];
      $ylegend = $thisgraph['ylegend'];
      if(isset($thisgraph['alpha'])) {
         $alpha = $thisgraph['alpha'];
         $color .= '@' . $alpha;
      }
      if(isset($thisgraph['overlapping'])) {
         $overlapping = $thisgraph['overlapping'];
      } else {
         $overlapping = 0;
      }
      if(isset($thisgraph['plottype'])) {
         $plottype = $thisgraph['plottype'];
      } else {
         $plottype = 'bar';
      }
      if (count($graphrecs) > 0) {
         $xdata = array();
         $ydata = array();
      } else {
         $xdata = array(0);
         $ydata = array(0);
      }

      $scalemax = 0;
      foreach ($graphrecs as $thisrec) {
         $xval = $thisrec[$xcol];
         $yval = $thisrec[$ycol];
         array_push($xdata, $xval);
         array_push($ydata, $yval);

         if ($yval > $scalemax) {
            $scalemax = $yval;
         }

      }
      $numx = count($xdata);
      $x_interval = intval($numx / $numxlabels);
      if (!($x_interval > 0)) {
         $x_interval = 1;
      }
      if ($debug) {
         print("X print interval = $x_interval <br>");
      }
      $graph->xaxis->SetTextLabelInterval($x_interval);

      # allows user to specify a second axis
      if(isset($thisgraph['yaxis'])) {
         $yaxis = $thisgraph['yaxis'];
      } else {
         $yaxis = 1;
      }

      switch ($yaxis) {
         case 1:
            // Create the bar plot
            $eplot[$x] = new BarPlot($ydata);
            $eplot[$x]->SetFillColor($color);
            $eplot[$x]->SetLegend($ylegend);
            // Add the plots to the graph
            if ($overlapping) {
               $graph->AddY2($eplot[$x]);
            }
            $x++;
         break;

         case 2:
            $y2type = $plottype;
            // Create the bar plot in 2nd yaxis array
            switch ($plottype) {
               case 'bar':
                  $eplot2[$x2] = new BarPlot($ydata);
                  $eplot2[$x2]->SetFillColor($color);
               break;

               case 'line':
                  $eplot2[$x2] = new LinePlot($ydata);
                  if(isset($thisgraph['mark'])) {
                     $mark = $thisgraph['mark'];
                     $eplot2[$x2]->mark->SetType($mark);
                  }
                  $eplot2[$x2]->SetColor($color);
                  if (isset($thisgraph['filled'])) {
                     if ($thisgraph['filled']) {
                        $eplot2[$x2]->SetFillColor($color);
                     }
                  }
               break;
            }

            $eplot2[$x2]->SetLegend($ylegend);
            // Add the plots to the graph
            if ($overlapping or ($plottype == 'line')) {
               $graph->AddY2($eplot2[$x2]);
               #print("Adding Plot Type = $plottype <br>");
            }
            $x2++;
         break;
      }

      array_push($axissss, $yaxis);
      if (count($xdata) > $maxrecs) {
         $graph->xaxis->SetTickLabels($xdata);
         $maxrecs = count($xdata);
      }
   }

   if (!$overlapping) {
      #print("side by side graph requested");
      if ($overlaptype == 'accum') {
         $gbarplot = new AccBarPlot($eplot);
      } else {
         $gbarplot = new GroupBarPlot($eplot);
      }
      $gbarplot->SetWidth(0.6);
      $graph->Add($gbarplot);
      if (in_array(2, $axissss)) {
         #$graph->ynaxis[0]->title->Set("$y2label");
         switch($y2type) {
            case 'bar':
               $gbarplot2 = new GroupBarPlot($eplot2);
               $gbarplot2->SetWidth(0.6);
               $graph->AddY2($gbarplot2);
               $graph->SetY2Scale("$y2scale");
            break;

            case 'line':
               # do nothing, since lines are always allowed to overlap, and will have been added earlier;
               $graph->SetY2Scale("$y2scale");
            break;
         }

      }
   }

   $graph->title->Set("$title");
   $graph->xaxis->title->Set("$xlabel");
   $graph->yaxis->title->Set("$ylabel");
   $graph->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->setLabelAngle($labelangle);

   // Display the graph
   if ( ($randomname) or (strlen($basename) == 0) ) {
      $gfname = "$ycol." . md5(uniqid(time())) . "." . DEFAULT_GFORMAT;
   } else {
      $gfname = $basename . "." . DEFAULT_GFORMAT;
   }
   $gpath = "$goutdir/$gfname";
   $gurl = "$gouturl/$gfname";
   $graph->Stroke($gpath);
   return $gurl;
}


function showGenericMultiLine($goutdir, $gouturl, $inrecs, $debug) {

   # $indata  - array containing multiple data sets and info describing these data sets
   # 'title' -0 title of the graph
   # 'xlabel' - label for X-axis
   # 'bargraphs' - a collection for each bar graph to create, containing the following:
   #    'graphrecs' - the records to graph
   #    'xcol' -
   #    'ycol' -
   #    'color' -
   #    'ylegend' - legend entry for this dataset

   # load data
   $bargraphs = $inrecs['bargraphs'];
   $title = $inrecs['title'];
   $xlabel = $inrecs['xlabel'];
   if(isset($inrecs['ylabel'])) {
      $ylabel = $inrecs['ylabel'];
   } else {
      $ylabel = "";
   }
   if(isset($inrecs['y2label'])) {
      $y2label = $inrecs['y2label'];
   } else {
      $y2label = "";
   }
   if(isset($inrecs['scale'])) {
      $scale = $inrecs['scale'];
   } else {
      $scale = "intlin";
   }
   error_log("'$title' Graph Scale set to $scale ");
   if(isset($inrecs['y2scale'])) {
      $y2scale = $inrecs['y2scale'];
   } else {
      $y2scale = "lin";
   }
   if (isset($inrecs['x_interval'])) {
      $x_interval = $inrecs['x_interval'];
   } else {
      $x_interval = 1;
   }
   if ($x_interval <= 0) {
      $x_interval = 1;
   }
   if ($debug) {
      $debugstring .= "X print interval = $x_interval <br>";
   }
   if (isset($inrecs['labelangle'])) {
      $labelangle = $inrecs['labelangle'];
   } else {
      $labelangle = 0.0;
   }
   if (isset($inrecs['gwidth'])) {
      $gwidth = $inrecs['gwidth'];
      $gheight = $inrecs['gheight'];
   } else {
      $gwidth = 400;
      $gheight = 200;
   }

   if ($debug) {
      $debugstring .= print_r($inrecs,1);
   }

   # set up the initial graph container
   // Create the graph.
   $graph = new Graph($gwidth,$gheight,"auto");
   # check to see if dimensions have been added for us
   if (isset($inrecs['ymax']) and isset($inrecs['ymin']) ) {
      if (isset($inrecs['xmax']) and isset($inrecs['xmin']) ) {
         $graph->SetScale("$scale", $inrecs['ymin'], $inrecs['ymax'], $inrecs['xmin'], $inrecs['xmax']);
      } else {
         $graph->SetScale("$scale", $inrecs['ymin'], $inrecs['ymax']);
      }
   } else {
      $graph->SetScale("$scale");
   }
   $xlabelmargin = $gheight * 0.15;
   $ylabelmargin = $gwidth * 0.1;
   # calculate legen margin from max legend text width
   $maxleg = 0;
   foreach ($bargraphs as $thisgraph) {
      $ylegend = $thisgraph['ylegend'];
      if (strlen($ylegend) > $maxleg) {
         $maxleg = strlen($ylegend);
      }
   }
   $legendmargin = $maxleg * 9 + 12;
   $xlabelmargin = $xlabelmargin + abs($xlabelmargin * sin(2.0*3.14159*$labelangle/360.0));
   $graph->img->SetMargin($ylabelmargin,$legendmargin,20,$xlabelmargin);
   $graph->SetShadow();

   $x = 0;
   $axissss = array();
   $maxrecs = 0;
   $error_code = 0;
   $gerror = '';
   foreach ($bargraphs as $thisgraph) {
      $graphrecs = $thisgraph['graphrecs'];
      $xcol = $thisgraph['xcol'];
      $ycol = $thisgraph['ycol'];
      $color = $thisgraph['color'];
      $ylegend = $thisgraph['ylegend'];
      # allows user to specify a second axis
      if(isset($thisgraph['yaxis'])) {
         $yaxis = $thisgraph['yaxis'];
      } else {
         $yaxis = 1;
      }
      if(isset($thisgraph['alpha'])) {
         $alpha = $thisgraph['alpha'];
         $color .= '@' . $alpha;
      }
      if (count($graphrecs) > 0) {
         $xdata = array();
         $ydata = array();
      } else {
         $xdata = array(0);
         $ydata = array(0);
      }

      $scalemax = 0;
      foreach ($graphrecs as $thisrec) {
         if (!in_array($xcol, array_keys($thisrec)) and ($error_code <> 1) ) {
            $gerror .= "Error: '$xcol' does not exist in " . print_r($thisrec,1) . " <br>\n";
            $error_code = 1;
            //break;
         }
         if (!in_array($ycol, array_keys($thisrec)) and ($error_code <> 1) ) {
            $gerror .= "Error: '$ycol' does not exist in" . print_r($thisrec,1) . "<br>\n";
            $error_code = 1;
            //break;
         }
         $yval = $thisrec[$ycol];
         array_push($ydata, $yval);
         if (strlen($xcol) > 0) {
            $xval = $thisrec[$xcol];
            array_push($xdata, $xval);
         }

         if ($yval > $scalemax) {
            $scalemax = $yval;
         }

      }
      $graph->xaxis->SetTextLabelInterval($x_interval);

      // Create the bar plot
      $eplot[$x] = new LinePlot($ydata);
      if(isset($thisgraph['fillcolor'])) {
         $fillcolor = $thisgraph['fillcolor'];
         if(isset($thisgraph['alpha'])) {
            $alpha = $thisgraph['alpha'];
            $fillcolor .= '@' . $alpha;
         }
         $eplot[$x]->SetFillColor($fillcolor);
      }
      if(isset($thisgraph['mark'])) {
         $mark = $thisgraph['mark'];
         $eplot[$x]->mark->SetType($mark);
      }
#      $eplot[$x]->SetFillColor($color);
      $eplot[$x]->SetColor($color);
      $eplot[$x]->SetLegend($ylegend);

      // Add the plots to the graph
      switch ($yaxis) {
         case 1:
            $graph->Add($eplot[$x]);
         break;

         case 2:
            $graph->AddY2($eplot[$x]);
            #$graph->AddY(2,$eplot[$x]);
         break;
         default:
            $graph->Add($eplot[$x]);
         break;
      }
      array_push($axissss, $yaxis);

      if (count($xdata) > $maxrecs) {
         $graph->xaxis->SetTickLabels($xdata);
         $maxrecs = count($xdata);
      }
      $x++;
   }
   $graph->xaxis->SetLabelAngle($labelangle);

   $graph->title->Set("$title");
   $graph->xaxis->title->Set("$xlabel");
   $graph->yaxis->title->Set("$ylabel");
   if (in_array(2, $axissss)) {
#      $graph->SetY2Title("$y2label", "middle");
#      $graph->ynaxis[2]->SetTitle("$y2label");
#      $graph->y2axis->title->SetMargin(5);
#      $graph->y2axis->title->SetFont(FF_FONT1,FS_BOLD);
      $graph->SetY2Scale("$y2scale");
   }
   $graph->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
   $graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
   if (isset($inrecs['color'])) {
      $graph->setColor($inrecs['color']);
   }

   // Display the graph
   if (isset($inrecs['filename'])) {
      $gfname = $inrecs['filename'] . "." . DEFAULT_GFORMAT;
   } else {
      $gfname = "$ycol." . md5(uniqid(time())) . "." . DEFAULT_GFORMAT;
   }
   error_log ("Multi-Line Graphic format set to " . DEFAULT_GFORMAT);
   $gpath = "$goutdir/$gfname";
   $gurl = "$gouturl/$gfname";
   if ($debug) {
      $debugstring .="Writing Image to $gpath <br>";
   }
   error_log ("Calling Graph->stroke($gpath) ");
   if ((!$error_code)) {
      @$graph->Stroke($gpath);
   } else {
      error_log("Graphing error in lib_plot.pgp - $gerror");
   }
   if ($debug) {
      $debugstring .= "Returning $gurl <br>";
   }
   error_log ("Returning $gurl <br>");
   return $gurl;
}

############################################################################

function splineEx($goutdir, $goutpath, $fname) {
   $xdata = array(1,3,5,7,9,12,15,17.1);
   $ydata = array(5,1,9,6,4,3,19,12);

   // Get the interpolated values by creating
   // a new Spline object.
   print("Creating Spline Object.<br>");
   $spline = new Spline($xdata,$ydata);

   // For the new data set we want 40 points to
   // get a smooth curve.
   list($newx,$newy) = $spline->Get(50);

   // Create the graph
   $g = new Graph(300,200);
   $g->SetMargin(30,20,40,30);
   print("Setting graph labels.<br>");
   $g->title->Set("Natural cubic splines");
   $g->title->SetFont(FF_ARIAL,FS_NORMAL,12);
   $g->subtitle->Set('(Control points shown in red)');
   $g->subtitle->SetColor('darkred');
   $g->SetMarginColor('lightblue');

   //$g->img->SetAntiAliasing();

   // We need a linlin scale since we provide both
   // x and y coordinates for the data points.
   $g->SetScale('linlin');

   // We want 1 decimal for the X-label
   $g->xaxis->SetLabelFormat('%1.1f');

   // We use a scatterplot to illustrate the original
   // contro points.
   $splot = new ScatterPlot($ydata,$xdata);

   //
   $splot->mark->SetFillColor('red@0.3');
   $splot->mark->SetColor('red@0.5');

   // And a line plot to stroke the smooth curve we got
   // from the original control points
   $lplot = new LinePlot($newy,$newx);
   $lplot->SetColor('navy');

   // Add the plots to the graph and stroke
   $g->Add($lplot);
   $g->Add($splot);

   $g->Stroke("$goutdir/$fname.gif");

   return "$goutpath/$fname.gif";
}

?>
